import { h, ref, render, type VNode, type Ref } from "vue"
import { Dialog, Field } from "vant";
import type { DialogOptions, FieldTextAlign } from "vant";

export default (message: string,
    options: DialogOptions & { target?: string, placeholder?: string, inputAlign?: FieldTextAlign } = {}, content?: string): Promise<string> => {
    const C: Ref<string> = ref(content || '')
    return new Promise((res: (value: string) => void, rej) => {
        const targetDom = document.querySelector(options.target || 'body')
        const Render = (dom: VNode) => {
            if (targetDom) render(dom, targetDom)
            else throw new Error('targetDom is not find')
        }
        const dom = h(Dialog, {
            show: true,
            ...options,
            onConfirm: () => {
                res(C.value)
                Render(h('div'))
            },
            onCancel: () => {
                rej()
                Render(h('div'))
            }, "onClickOverlay": () => Render(h('div'))
        },
            {
                default: () =>
                    [message && h('div', { className: 'apppadding', style: 'color:#666;font-size:0.9em;padding-bottom:0' }, message),
                    h(Field, {
                        placeholder: options.placeholder, inputAlign: options.inputAlign,
                        modelValue: C.value, "onUpdate:modelValue": (val: string) => { C.value = val }
                    })],
            })
        Render(dom)
    })
}